package com.kcl.dfss;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.kcl.dfss.adapter.AccountAdapter;
import com.kcl.dfss.http.ServerConnection;

public class PersonalAccountActivity extends Activity {

	private Button btn_logout;

	private String[] items = { "选择本地照片", "拍照" };
	private static final int NONE = 0;
	private static final int PHOTO_GRAPH = 1;// 拍照
	private static final int PHOTO_ZOOM = 2; // 缩放
	private static final int PHOTO_RESOULT = 3;// 结果
	private static final String IMAGE_UNSPECIFIED = "image/*";

	private static final String tag = "PersonalAccountActivity";
	private String path;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_personal_account);

		ListView account_list = (ListView) findViewById(R.id.account_list);

		ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
		SharedPreferences shared = getSharedPreferences("shared_login", 0);
		String phone = shared.getString("phone", " ");
		final String usernick = shared.getString("usernick", " ");
		String data[] = { "账户名," + usernick, "电话," + phone, "头像编辑", "修改密码" };
		int type[] = { 0, 0, 1, 1 };
		for (int i = 0; i < data.length; i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("data", data[i]);
			listItem.add(map);
		}

		AccountAdapter accountAdapter = new AccountAdapter(listItem, this, type);
		account_list.setAdapter(accountAdapter);

		account_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0:
					Intent intent = new Intent();
					intent.putExtra("usernick", usernick);
					intent.setClass(PersonalAccountActivity.this, ChangeNickActivity.class);
					startActivity(intent);
					break;
				case 1:
					break;
				case 2:
					showDialog();
					break;
				case 3:
					startActivity(new Intent(PersonalAccountActivity.this,
							ChangePwd1Activity.class));
					break;
				}
			}
		});

		LinearLayout personal_account_back = (LinearLayout) findViewById(R.id.personal_account_back);
		personal_account_back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		// 退出登录
		btn_logout = (Button) findViewById(R.id.btn_logout);
		btn_logout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SharedPreferences preferences = getSharedPreferences(
						"shared_login", 0);
				preferences.edit().putBoolean("login", false).commit();
				preferences.edit().putString("userid", null).commit();
				preferences.edit().putString("userpattern", null).commit();
				preferences.edit().putString("phone", null).commit();
				preferences.edit().putString("userhead", null).commit();
				Intent intent = new Intent();
				intent.setClass(PersonalAccountActivity.this,MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra("flag", 2);
				startActivity(intent);
				finish();
			}
		});

	}

	private void showDialog() {
		new AlertDialog.Builder(this)
				.setTitle("编辑头像")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							Intent intent = new Intent(Intent.ACTION_PICK);
							intent.setDataAndType(
									MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
									IMAGE_UNSPECIFIED);
							startActivityForResult(intent, PHOTO_ZOOM);
							break;
						case 1:
							Intent intnt = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							intnt.putExtra(MediaStore.EXTRA_OUTPUT, Uri
									.fromFile(new File(Environment
											.getExternalStorageDirectory(),
											"temp.jpg")));
							startActivityForResult(intnt, PHOTO_GRAPH);
							break;
						}
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == NONE)
			return;
		// 拍照
		if (requestCode == PHOTO_GRAPH) {
			// 设置文件保存路径
			File picture = new File(Environment.getExternalStorageDirectory()
					+ "/temp.jpg");
			path = Environment.getExternalStorageDirectory() + "/temp.jpg";
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// 读取相册缩放图片
		if (requestCode == PHOTO_ZOOM) {
			Uri uri = data.getData();
			startPhotoZoom(uri);
		}
		// 处理结果
		if (requestCode == PHOTO_RESOULT) {
			try {
				Bitmap bm = null;
				Bundle bundle = data.getExtras();
				bm = (Bitmap) bundle.get("data"); // 先得到bitmap图片
				path = Environment.getExternalStorageDirectory() + "/temp.jpg";
				savePhotoTo(bm,path);

				final SharedPreferences preferences = getSharedPreferences(
						"shared_login", 0);
				final String userid = preferences.getString("userid", "");
				final File file = new File(path);
				new Thread(new Runnable() {
					@Override
					public void run() {
						final String result = ServerConnection.UpdateHead(
								userid, file);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								try {
									JSONObject jsonObject = new JSONObject(result);
									String getresult = jsonObject.getString("success");
									String data = jsonObject.getString("data");
									JSONObject jsondata = new JSONObject(data);
									String userhead = jsondata.getString("userhead");
									preferences.edit().putString("userhead", userhead).commit();
									if (getresult.equals("true")) {
										Toast.makeText(
												PersonalAccountActivity.this,
												"头像上传成功", Toast.LENGTH_SHORT)
												.show();
										preferences.edit().putBoolean("newhead", true).commit();
									} else {
										Toast.makeText(
												PersonalAccountActivity.this,
												"头像上传失败", Toast.LENGTH_SHORT)
												.show();
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						});
					}
				}).start();
				//
			} catch (Exception e) {

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");// 调用Android系统自带的一个图片剪裁页面,
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");// 进行修剪
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTO_RESOULT);
	}

	public void savePhotoTo(Bitmap bmp, String path) {

		File myCaptureFile = new File(path);
		BufferedOutputStream bos;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
			bmp.compress(Bitmap.CompressFormat.JPEG, 80, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
